package newbond

import (
	"encoding/json"
	"log"
	"strconv"
	"strings"
	"time"
	"xiaoniu-task/pkg/feishu"
	"xiaoniu-task/pkg/req"
)

type Res struct {
	Rows []Row `json:"rows"`
}

type Row struct {
	Id   string `json:"id"`
	Cell Cell   `json:"cell"`
}

type Cell struct {
	// 转债名称
	BondName string `json:"bond_nm"`
	// 转债类型
	BondType string `json:"cb_type"`
	// 申购日期
	ApplyDate string `json:"apply_date"`
	// 申购提示
	ApplyTips string `json:"apply_tips"`
}

// DoJob 获取今日的可转债信息
func DoJob(taskLog *log.Logger) {
	// 请求集思录获取可转债列表
	url := "https://www.jisilu.cn/data/cbnew/pre_list/?___jsl=LST___t=" + strconv.FormatInt(GetTimestamp(), 10)
	params := make(map[string]string)
	params["progress"] = ""
	params["rp"] = "22"
	response := req.PostUrlencoded(url, params)
	if response == "" {
		taskLog.Println("没有获取到数据！")
	} else {
		var newBondRes Res
		err := json.Unmarshal([]byte(response), &newBondRes)
		if err != nil {
			taskLog.Println("JSON转换出错！")
			feishu.PushText("新债爬虫出错：" + response)
		} else {
			builder := strings.Builder{}
			for _, row := range newBondRes.Rows {
				// 判断申购日期为今天的可转债
				if IsToday(row.Cell.ApplyDate) {
					builder.WriteString("转债名称：" + row.Cell.BondName + "\n")
					builder.WriteString("转债类型：" + row.Cell.BondType + "\n")
					builder.WriteString("申购日期：" + row.Cell.ApplyDate + "\n")
					builder.WriteString("申购提示：" + row.Cell.ApplyTips + "\n\n")
				}
			}
			if builder.Len() == 0 {
				feishu.PushText("今日没有新债需要申购！")
			} else {
				feishu.PushText(builder.String())
			}
		}
	}
	taskLog.Println("任务执行完成！")
}

// GetTimestamp 获取当前时间戳
func GetTimestamp() int64 {
	return time.Now().UnixNano() / 1e6
}

// IsToday 判断日期是否为今天
func IsToday(date string) bool {
	if date == "" {
		return false
	}
	return date == time.Now().Format("2006-01-02")
}
